import { useState, useEffect, useImperativeHandle, RefObject } from 'react';
import { Form, Input, message, Modal, Select, TreeSelect } from 'antd';
import { IDept, IUser } from '../../types/api';
import api from '../../api';

interface IProps {
  mref?: RefObject<{ openModal: () => void }>;
  update?: () => void;
}

//新增功能
const CreateDept = (props: IProps) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [deptList, setDeptList] = useState<IDept[]>(); //部门列表
  const [userList, setUserList] = useState<IUser[]>(); //用户列表
  const [form] = Form.useForm();

  //获取所有用户信息
  useEffect(() => {
    getAllUserList();
  }, []);

  //获取部门列表
  const getDeptData = async () => {
    const data = await api.getDeptList();
    setDeptList(data);
  };

  //获取用户列表
  const getAllUserList = async () => {
    const data = await api.getAllUserList();
    setUserList(data);
  };

  const handleOk = async () => {
    //校验
    const valid = await form.validateFields();
    if (!valid) return;
    await api.createDept(form.getFieldsValue());
    setIsModalOpen(false);
    handleCancel();
    message.success('创建成功');
    props.update && props.update();
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
  };

  //打开弹框
  const openModal = () => {
    setIsModalOpen(true);
    getDeptData();
  };
  useImperativeHandle(props.mref, () => ({ openModal }));

  return (
    <>
      <Modal
        title='创建部门'
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        maskClosable={false} //点击蒙层不关闭
      >
        <Form labelAlign='right' labelCol={{ span: 4 }} form={form}>
          <Form.Item label='上级部门' name='parent'>
            <TreeSelect
              placeholder='请选择上级部门'
              allowClear
              treeDefaultExpandAll
              treeData={deptList}
              fieldNames={{
                label: 'deptName',
                value: '_id',
              }}
            />
          </Form.Item>
          <Form.Item
            label='部门名称'
            name='deptName'
            rules={[{ required: true, message: '请输入部门名称' }]}
          >
            <Input placeholder='请输入部门名称'></Input>
          </Form.Item>
          <Form.Item
            label='负责人'
            name='userName'
            rules={[{ required: true, message: '请选择负责人' }]}
          >
            <Select>
              {userList?.map((item) => {
                return (
                  <Select.Option key={item._id} value={item._id}>
                    {item.userName}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default CreateDept;
